<template>
  <div>
    <div class="home" v-if="isAuth">
      <search-bar
        @onClick="onSearchBarClick"
        :hotSearch="hotSearch"
        :focus="focus"
        ref="searchBar"
      ></search-bar>

      <HomeCard
        :data="homeCard"
        @onBookClick="(item)=>onBookClick(item)"
        @gotoShelf="(userInfo)=>gotoShelf(userInfo)"
      />

      <home-banner
        title="mpvue2.0多端小程序课程重磅上线"
        subTitle="立即体验"
      ></home-banner>

      <home-book
        title="为你推荐"
        :row="1"
        :col="3"
        :data="recommend"
        mode="col"
        btnText="换一批"
        height="147px"
        width="101px"
        @onMoreClick="recommendChange('recommend')"
        @onBookClick="(item)=>onHomeBookClick(item)"
      ></home-book>

      <home-book
        title="免费阅读"
        :row="2"
        :col="2"
        :data="freeRead"
        mode="row"
        btnText="换一批"
        @onMoreClick="recommendChange('freeRead')"
        @onBookClick="(item)=>onHomeBookClick(item)"
      ></home-book>

      <home-book
        title="当前最热"
        :row="1"
        :col="4"
        :data="hotBook"
        mode="col"
        height="99px"
        width="68px"
        btnText="换一批"
        @onMoreClick="recommendChange('hotBook')"
        @onBookClick="(item)=>onCategoryClick(item)"
      ></home-book>

      <home-book
        title="分类"
        :row="2"
        :col="2"
        :data="category"
        mode="category"
        btnText="查看全部"
        @onMoreClick="onCategoryMoreClick"
        @onBookClick="(item)=>onCategoryClick(item)"
      ></home-book>
    </div>
    <auth v-if="!isAuth" @getUserInfo="init"></auth>
  </div>
</template>

<script>
  import { getAllHomeData, getRecommend, getFreeRead, getHotBook,register } from "../../api/index";
  import SearchBar from "../../components/home/SearchBar.vue";
  import HomeCard from "../../components/home/HomeCard.vue";
  import HomeBanner from "../../components/home/HomeBanner.vue";
  import HomeBook from "../../components/home/HomeBook.vue";
  import { getSetting,getUserInfo,setStorageSync,getStorageSync,getUserOpenId,showLoading,hideLoading } from "../../api/wechat";
  import Auth from '../../components/base/Auth.vue';
  export default {
    data() {
      return {
        banner: {},    //广告信息
        category: [],  //分类
        freeRead: [],  //免费阅读
        homeCard: {},  //书架详情
        recommend: [], //推荐
        hotBook: [],   //当前最热门
        hotSearch: "",  //热门关键词
        isAuth : true,
        openId : '不能为空',
        index : null,
      };
    },
    computed : {
    },
    mounted() {
      this.init(); //获取openid错误
      //this.getHomeData();
    },
    methods: {
      init(){ //用户初始化
        this.getSetting();
      },
      getSetting() {
        getSetting(     //获取用户授权
          "userInfo",
          () => {
            console.log("授权成功");
            this.isAuth = true;
            showLoading();
            this.getUserInfo();
          },
          () => {
            console.log("授权失败");
            this.isAuth = false;
          }
        );
      },
      getUserInfo(e){  //获取用户信息
        const onOpenIdComplete = (openId,userInfo)=>{
          this.getHomeData(openId,userInfo);
          register(openId,userInfo);
        };
        getUserInfo((userInfo)=>{
          this.isAuth = true;
          setStorageSync('userInfo',userInfo);
          const openId = getStorageSync('openId');
          if (!openId || openId.length === 0){
            console.log("需要获取openId");
            //通过获取到的openid传递给register函数，该函数再注册用户信息
            getUserOpenId(openId =>onOpenIdComplete(openId,userInfo));
            hideLoading();
          }else{
            onOpenIdComplete(openId,userInfo);
            hideLoading();
            console.log("加载完毕");
          }
        },(res)=>{
          console.log(res);
        });
      },
      recommendChange(key) {
        this.$refs.searchBar.focus = false;
        switch (key) {
          case "recommend":
            getRecommend().then(response => {
              this.recommend = response.data.data;
            });
            break;
          case "freeRead":
            getFreeRead().then(response => {
              this.freeRead = response.data.data;
            });
            break;
          case "hotBook":
            getHotBook().then(response => {
              this.hotBook = response.data.data;
            });
            break;
        }
      },
      getHomeData(openId,userInfo) { //获取首页数据
        getAllHomeData({ openId }).then(response => {
          let res = response.data.data;
          const {
            banner,
            category,
            freeRead,
            shelf,
            recommend,
            hotBook,
            hotSearch: {
              keyword
            },
            shelfCount
          } = res;
          this.banner = banner;
          this.category = category;
          this.freeRead = freeRead;
          this.recommend = recommend;
          this.hotBook = hotBook;
          this.hotSearch = keyword;
          this.homeCard = {
            bookList: shelf,
            num: shelfCount,
            userInfo: userInfo
          };
        });
      },
      onBookClick(item) {  //card书本点击
        this.$router.push({
          path : '/pages/detail/main',
          query : {
            fileName : item.fileName,
          },
        })
      },
      onCategoryMoreClick() {  //查看全部
        this.$router.push({
          path : '/pages/categoryList/main'
        })
      },
      onSearchBarClick() { //跳转到搜索页
        this.$router.push({
          path : '/pages/search/main'
        })
      },
      onBannerClick() {  //广告点击

      },
      onHomeBookClick(book) {    //图书点击事件
        let fileName = book.fileName;
        this.$router.push({
          path : '/pages/detail/main',
          query:{
            fileName
          }
        })
      },
      onCategoryClick(item){
        let category = item.categoryText;
        this.$router.push({
          path : '/pages/list/main',
          query:{
            category
          }
        });
      },
      gotoShelf(userInfo){
        const { avatarUrl,nickName } = userInfo;
        this.$router.push({
          path : '/pages/shelf/main',
          query : {
            avatarUrl,
            nickName
          }
        });
      },
    },
    components: {
      SearchBar,
      HomeCard,
      HomeBanner,
      HomeBook,
      Auth,
    }
  };
</script>

<style lang="less" scoped>
  .home {
    padding: 0 15px;
  }

</style>
